<template>
  <div>
    <el-row :gutter="10" class="containerView">
      <!--table-->
      <el-col :span="24" :xs="24" class="mainHeight">
        <el-card shadow="always" class="mainHeight">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="" prop="keyword">
              <!-- <el-select
                @change="changeSelectHandle"
                v-model="queryParams.senseId"
                placeholder="请选择所属区域"
              >
                <el-option
                  v-for="item in senceList"
                  :key="item.senseId"
                  :label="item.name"
                  :value="item.senseId"
                >
                </el-option>
              </el-select> -->
            </el-form-item>

            <el-form-item style="float: right">
              <el-button
                @click="reset"
                plain
                icon="el-icon-refresh"
                size="small"
                >刷新</el-button
              >
              <el-button
                @click="addHandle"
                type="primary"
                size="small"
                icon="el-icon-plus"
                >添加</el-button
              >
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="tableList"
            height="70vh"
            style="width: 100%"
            default-expand-all
          >
            <el-table-column
              label="学校编号"
              prop="id"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="学校名称"
              prop="name"
              :show-overflow-tooltip="true"
            >
            </el-table-column>

            <el-table-column
              label="创建时间"
              prop="created_at"
              :show-overflow-tooltip="true"
            ></el-table-column>

            <el-table-column
              width="200"
              label="操作"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="updateHandle(scope.row)"
                  >编辑</el-button
                >

                <el-button
                  class="text-danger"
                  type="text"
                  size="mini"
                  @click="deleteHandle(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.page_size"
            @pagination="getCustomersListHandle"
          />
        </el-card>
        <el-dialog
          :title="editShow ? '编辑学校' : '添加学校'"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          destroy-on-close
          width="500px"
        >
          <el-form
            :rules="formRules"
            ref="elForm"
            :model="formData"
            class="my-form"
            size="medium"
            label-width="100px"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="所属城市" prop="city_id">
                  <el-select
                    v-model="formData.city_id"
                    placeholder="请选择所属城市"
                    style="width: 336px"
                  >
                    <el-option
                      v-for="item in cityList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="学校名称" prop="name">
                  <el-input
                    v-model="formData.name"
                    placeholder="请输入学校名称"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="dialogVisible = false"
              >取消</el-button
            >
            <el-button size="small" type="primary" @click="addCardStylesHandle"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  customersList,
  customersCategoriesList,
  customerSourcesList,
  customerStatusesList,
  addCustomers,
  editCustomers,
  delCustomers,
  getContactsList,
  addContacts,
  editContacts,
  delContacts,
  invoiceSubjects,
  addInvoiceSubjects,
  editInvoiceSubjects,
  delInvoiceSubjects,
  customersDetail,
  citiesList,
} from "@/api/custmoer";

import { getJobPositionsList } from "@/api/system/position";
import { getPaymentPeriodsList } from "@/api/system/paymentPeriods";
import { getToken } from "@/utils/auth";
export default {
  name: "Customer",
  data() {
    return {
      filterText: "",
      // 遮罩层
      loading: false,
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 15,
      },

      tableList: [],
      senceList: [],
      areaList: [],
      editShow: false,
      formData: {
        id: "",
        city_id: "",
        name: "",
      },

      formRules: {
        city_id: [
          { required: true, trigger: "blur", message: "请选择所属城市" },
        ],
        name: [{ required: true, trigger: "blur", message: "请输入学校名称" }],
      },
      dialogVisible: false,
      updateShow: false,

      newAreaList: [],
      ruleLoading: false,
      actionUrl: "",
      header: {
        Authorization: "Bearer " + getToken(),
      },
      statusList: [],
      sourceList: [],
      categoriesList: [],
      contactsList: [],
      contactsDialogVisible: false,
      contactsFormData: {
        id: "",
        customer_id: "",
        name: "",
        phone: "",
        address: "",
        job_position_id: "",
        is_employed: "",
        remark: "",
        payment_period_id: "",
        period_days: "",
        archive_data: "",
        business_license: "",
      },
      contactsFormRules: {
        customer_id: [
          { required: true, trigger: "blur", message: "请选择客户" },
        ],
        name: [
          { required: true, trigger: "blur", message: "请输入联系人姓名" },
        ],
        phone: [
          { required: true, trigger: "blur", message: "请输入联系人电话" },
        ],
        address: [
          { required: true, trigger: "blur", message: "请输入联系人地址" },
        ],
        job_position_id: [
          { required: true, trigger: "blur", message: "请选择岗位" },
        ],
        is_employed: [
          { required: true, trigger: "blur", message: "请选择是否在职" },
        ],
      },
      contactsAddDialogVisible: false,
      editContactShow: false,
      subjectsList: [],
      invoiceSubjectsDialogVisible: false,
      invoiceSubjectsFormData: {
        id: "",
        customer_id: "",
        header: "",
        tax_number: "",
        bank_name: "",
        bank_account: "",
        phone: "",
        address: "",
      },
      invoiceSubjectsFormRules: {
        customer_id: [
          { required: true, trigger: "blur", message: "请选择客户" },
        ],
        header: [{ required: true, trigger: "blur", message: "请输入抬头" }],
        tax_number: [
          { required: true, trigger: "blur", message: "请输入税号" },
        ],
        bank_name: [
          { required: true, trigger: "blur", message: "请输入银行名称" },
        ],
        bank_account: [
          { required: true, trigger: "blur", message: "请输入银行账号" },
        ],
        phone: [{ required: true, trigger: "blur", message: "请输入手机号" }],
        address: [{ required: true, trigger: "blur", message: "请输入地址" }],
      },
      editSubjectShow: false,
      subjectsAddDialogVisible: false,
      jobPositionsList: [],
      paymentPeriodsList: [],
      archive_dataUrl: "",
      business_licenseUrl: "",
      cityList: [],
    };
  },
  watch: {},
  created() {
    this.getCustomersListHandle();
    this.citiesListHandle();
    // this.customerStatusesListHandle();
    // this.customerSourcesListHandle()
    // this.customersCategoriesListHandle()
    // this.getJobPositionsListHandle()
    // this.getPaymentPeriodsListHandle();
  },
  methods: {
    citiesListHandle() {
      citiesList().then((res) => {
        this.cityList = res.data;
      });
    },
    downloadBusinessLicense() {
      window.open(this.business_licenseUrl);
    },

    downloadArchive() {
      window.open(this.archive_dataUrl);
    },
    delBusinessLicenseData() {
      this.formData.business_license = "";
      this.business_licenseUrl = "";
      this.$forceUpdate();
    },

    delArchiveData() {
      this.formData.archive_data = "";
      this.archive_dataUrl = "";
      this.$forceUpdate();
    },
    handleBusinessLicenseSuccess(res) {
      let that = this;
      if (res.path) {
        that.formData.business_license = res.path;
        that.business_licenseUrl = res.url;
        that.$forceUpdate();
      } else {
        that.$message.error("上传失败请重试");
      }
    },
    handleArchiveSuccess(res) {
      let that = this;
      if (res.path) {
        that.formData.archive_data = res.path;
        that.archive_dataUrl = res.url;
        that.$forceUpdate();
      } else {
        that.$message.error("上传失败请重试");
      }
    },
    getPaymentPeriodsListHandle() {
      getPaymentPeriodsList()
        .then((res) => {
          this.paymentPeriodsList = res.data;
        })
        .catch((error) => {});
    },
    getJobPositionsListHandle() {
      getJobPositionsList().then((res) => {
        this.jobPositionsList = res.data;
      });
    },
    //删除开票资料
    delSubjectsHandle(row) {
      this.$modal.confirm("是否确认删除此条数据？").then(() => {
        delInvoiceSubjects({ id: row.id }).then((res) => {
          this.$message.success("删除成功");
          this.getInvoiceSubjectsHandle();
        });
      });
    },
    delContactsHandle(row) {
      this.$modal.confirm("是否确认删除此条数据？").then(() => {
        delContacts({ id: row.id }).then((res) => {
          this.$message.success("删除成功");
          this.getContactsListHandle();
        });
      });
    },
    //编辑开票资料
    addSubjectsHandle(row) {
      this.$refs.addsubjectForm.validate((valid) => {
        if (valid) {
          if (this.editSubjectShow) {
            editInvoiceSubjects(this.invoiceSubjectsFormData).then((res) => {
              this.$message.success("编辑成功");
              this.subjectsAddDialogVisible = false;
              this.getInvoiceSubjectsHandle();
            });
          } else {
            addInvoiceSubjects(this.invoiceSubjectsFormData).then((res) => {
              this.$message.success("添加成功");
              this.subjectsAddDialogVisible = false;
              this.getInvoiceSubjectsHandle();
            });
          }
        }
      });
    },

    // 编辑联系人
    addContactsHandle() {
      this.$refs.addContactForm.validate((valid) => {
        console.log(this.contactsFormData);
        if (valid) {
          if (this.editContactShow) {
            editContacts(this.contactsFormData).then((res) => {
              this.$message.success("编辑成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          } else {
            addContacts(this.contactsFormData).then((res) => {
              this.$message.success("添加成功");
              this.contactsAddDialogVisible = false;
              this.getContactsListHandle();
            });
          }
        }
      });
    },
    // 编辑开票资料
    editSubjectsHandle(row) {
      this.subjectsAddDialogVisible = true;
      this.invoiceSubjectsFormData.customer_id =
        this.invoiceSubjectsFormData.customer_id;
      this.invoiceSubjectsFormData.id = row.id;
      this.invoiceSubjectsFormData.header = row.header;
      this.invoiceSubjectsFormData.tax_number = row.tax_number;
      this.invoiceSubjectsFormData.bank_name = row.bank_name;
      this.invoiceSubjectsFormData.bank_account = row.bank_account;
      this.invoiceSubjectsFormData.phone = row.phone;
      this.invoiceSubjectsFormData.address = row.address;
      this.editSubjectShow = true;
    },
    // 编辑联系人
    editContactsHandle(row) {
      this.contactsAddDialogVisible = true;
      this.contactsFormData.customer_id = this.contactsFormData.customer_id;
      this.contactsFormData.id = row.id;
      this.contactsFormData.name = row.name;
      this.contactsFormData.phone = row.phone;
      this.contactsFormData.address = row.address;
      this.contactsFormData.job_position_id = row.job_position.id;
      this.contactsFormData.is_employed = row.is_employed;
      this.contactsFormData.remark = row.remark;
      this.editContactShow = true;
    },

    //点击开票资料
    clickSubjectsIdHandle(row) {
      this.invoiceSubjectsFormData.customer_id = row.id;
      this.getInvoiceSubjectsHandle();
    },

    customerStatusesListHandle() {
      customerStatusesList().then((res) => {
        this.statusList = res.data;
      });
    },
    customerSourcesListHandle() {
      customerSourcesList().then((res) => {
        this.sourceList = res.data;
      });
    },
    customersCategoriesListHandle() {
      customersCategoriesList().then((res) => {
        this.categoriesList = res.data;
      });
    },
    addCardStylesHandle() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          if (this.editShow) {
            editCustomers(this.formData).then((res) => {
              this.$message.success("编辑成功");
              this.dialogVisible = false;
              this.getCustomersListHandle();
            });
          } else {
            addCustomers(this.formData).then((res) => {
              this.$message.success("添加成功");
              this.dialogVisible = false;
              this.getCustomersListHandle();
            });
          }
        }
      });
    },
    handleAvatarSuccess(res, file) {
      let that = this;
      that.formData.image = res.path;
      that.Imgurl = res.url;
      that.$forceUpdate(); // 强制更新视图
    },
    beforeAvatarUpload(file) {},
    getCustomersListHandle() {
      this.loading = true;
      customersList(this.queryParams)
        .then((res) => {
          this.tableList = res.data;
          this.total = res.meta.total;
          this.loading = false;
          console.log(this.tableList);
        })
        .catch((error) => {
          this.loading = false;
        });
    },

    deleteHandle(row) {
      this.$modal
        .confirm("是否确认删除此条数据？")
        .then(async () => {
          const { code } = await delCustomers({
            id: row.id,
          });
          this.$message.success("删除成功");
          this.getCustomersListHandle();
        })
        .then(() => {})
        .catch(() => {});
    },

    updateHandle(cell) {
      let data = JSON.parse(JSON.stringify(cell));
      this.formData.id = data.id;
      this.formData.name = data.name;

      this.editShow = true;
      this.dialogVisible = true;
    },
    addHandle() {
      this.editShow = false;
      this.dialogVisible = true;
      this.formData = {
        id: "",

        name: "",
      };
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getCategories(6, {
        format: "tree",
      }).then((res) => {
        if (res.code == 0) {
          this.deptOptions = res.data.categories;
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (this.queryParams.paper_type == data.id) {
        this.queryParams.paper_type = undefined;
      } else {
        this.queryParams.paper_type = data.id;
      }

      this.handleQuery();
    },

    // 表单重置
    reset() {
      this.queryParams = {
        page: 1,
        page_size: 15,
        
      };
      this.filterText = undefined;
      this.getCustomersListHandle();
    },

    handleDelete() {
      const ids = this.ids;
      console.log(this.ids);
      this.$modal
        .confirm('是否确认删除编号ID为"' + ids + '"的数据项？')
        .then(async () => {
          const { code } = await delPaper({
            ids: this.ids,
          });
          console.log(1);
          if (code === 0) {
            this.$message.success("删除成功");
            this.handleQuery();
          }
          // return delUser(userIds);
        })
        .then(() => {
          console.log(2);
          // this.getList();
          // this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          console.log(3);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleImageError(event) {
      console.error("图片加载失败:", event.target.src);
      this.$message.error("图片加载失败，请检查图片地址或网络连接");
    },
  },
};
</script>
<style scoped scss>
@import url("~@/assets/styles/dialog_wangpx.scss");
.th {
  word-break: break-word;
  background-color: #f8f8f9;
  color: #515a6e;
  font-weight: 700;
  height: 40px;
  font-size: 13px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #dfe6ec;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: none;
}
</style>
